<?php
/*
Plugin Name: GoogleAnalyticsCounter
Plugin URI: http://www.yellingnews.com/wordpress-plugins
Description: Displays your visits from Google Analytics in a Feedburner like style in the sidebar of your blog via widget interface or anywhere else via function call. <strong><a href="options-general.php?page=googleanalyticscounter/googleanalyticscounter.php">CONFIGURE</a> your plugin first!</strong> Check out more <a href="http://www.yellingnews.com/wordpress-plugins">Wordpress Plugins</a> brought to you by Yellingnews <a href="http://www.yellingnews.com">Gadgets</a>.
Version: 0.5
Author: yellingnews
Author URI: http://www.yellingnews.com
*/
 
/**
 * v0.5 03.07.2009 added fallback method for automated analytics code injection
 * v0.4 02.07.2009 fixed caching, added automated analytics code injection, added check for curl extension
 * v0.3 27.06.2009 updated admin panel for better usability
 * v0.2 26.06.2009 better error handling in google api class
 * v0.1 26.06.2009 initial release
 */
 
if(!class_exists('GoogleAnalyticsCounter')):
class GoogleAnalyticsCounter {
  var $id;
  var $title;
  var $plugin_url;
  var $version;
  var $name;
  var $url;
  var $options;
  var $cache_file;
  var $locale;
  var $layouts;
  var $injected;

  function GoogleAnalyticsCounter() {
    $this->id         = 'googleanalyticscounter';
    $this->title      = 'GoogleAnalyticsCounter';
    $this->version    = '0.5';
    $this->plugin_url = 'http://www.yellingnews.com/wordpress-plugins';
    $this->name       = 'GoogleAnalyticsCounter v'. $this->version;
    $this->url        = get_bloginfo('wpurl'). '/wp-content/plugins/' . $this->id;
	  $this->locale     = get_locale();
    $this->path       = dirname(__FILE__);
    $this->injected   = false;

    $this->layouts    = array(
      array(
        'icon'  => 'counter0.gif',
        'color' => 'ffffff',
        'font'  => 3,
        'x'     => 5,
        'y'     => 2
      ),
      array(
        'icon'  => 'counter1.gif',
        'color' => '000000', #696969
        'font'  => 3,
        'x'     => 5,
        'y'     => 2
      ),
      array(
        'icon'  => 'counter2.gif',
        'color' => '000000',
        'font'  => 3,
        'x'     => 5,
        'y'     => 2
      ),
      array(
        'icon'  => 'counter4.gif',
        'color' => 'ffffff',
        'font'  => 3,
        'x'     => 5,
        'y'     => 2
      )
    );

	  if(empty($this->locale)) {
		  $this->locale = 'en_US';
    }

    load_textdomain($this->id, sprintf('%s/%s.mo', $this->path, $this->locale));

    $this->loadOptions();

    $this->cache_file = $this->path. '/cache/layout'. $this->options['layout']. '.gif';

    if(is_admin()) {
      add_action('admin_menu', array( &$this, 'optionMenu')); 
    }
    else {
      add_filter('wp_footer', array(&$this, 'blogFooter'));
      add_filter('wp_head', array(&$this, 'blogHeader'));
    }

    add_action('widgets_init', array( &$this, 'initWidget')); 
  }

  function optionMenu() {
    add_options_page($this->title, $this->title, 8, __FILE__, array(&$this, 'optionMenuPage'));
  }
  
  function listAccounts() {
    
    include_once($this->path . '/lib/googleanalyticsapi.class.php');
    
    $api = new GoogleAnalyticsApi($this->options['username'], $this->options['password']);
    
    $accounts = $api->getAccounts();
    
    $data = '';

    if($accounts !== false) {
      foreach($accounts as $k => $v) {
        $data .= sprintf('<option value="%s"%s>%s</option>', $k, $k == $this->options['account'] ? ' selected="selected"' : '', $v);
      }
    }

    return $data;
  }

  function optionMenuPage() {
?>
<div class="wrap">
<h2><?=$this->title?></h2>
<div align="center"><p><?=$this->name?> <a href="<?php print( $this->plugin_url ); ?>" target="_blank">Plugin Homepage</a></p></div> 
<?php
  if(isset($_POST[$this->id])) {

    @unlink($this->cache_file);
      
    $this->updateOptions($_POST[$this->id]);

    echo '<div id="message" class="updated fade"><p><strong>' . __( 'Settings saved! - Remember to flush your cache!', $this->id ) . '</strong></p></div>'; 
  }
?>
<form method="post" action="options-general.php?page=<?=$this->id?>/<?=$this->id?>.php">

<table class="form-table">
<?php if(!file_exists($this->path.'/cache/') || !is_writeable($this->path.'/cache/')): ?>
<tr valign="top"><th scope="row" colspan="4"><span style="color:red;"><?php _e('Warning! The cachedirectory is missing or not writeable!', $this->id); ?></span><br /><em><?php echo $this->path; ?>/cache</em></th></tr>
<?php endif; ?>
<tr valign="top">
  <th scope="row" colspan="4"><?php _e('Fill out these information first! Click save - than select the other options below. Click save again!', $this->id); ?></td>
</tr>
<tr valign="top">
  <th scope="row"><?php _e('Google Username', $this->id); ?></th>
  <td colspan="3"><input name="googleanalyticscounter[username]" type="text" id="" class="code" value="<?=$this->options['username']?>" /> <?php _e('The email you user as your Google-Account username.', $this->id); ?></td>
</tr>

<tr valign="top">
  <th scope="row"><?php _e('Google Password', $this->id); ?></th>
  <td colspan="3"><input name="googleanalyticscounter[password]" type="password" id="" class="code" value="<?=$this->options['password']?>" /></td>
</tr>
</table>

<p class="submit">
  <input type="submit" name="Submit" value="<?php _e('save', $this->id); ?>" class="button" />
</p>

<table class="form-table">
<tr valign="top">
  <th scope="row"><?php _e('Analytics Account', $this->id); ?></th>
  <td colspan="3">
  <select name="googleanalyticscounter[account]" class="code">
  <?php echo $this->listAccounts(); ?>
  </select>
  <?php _e('You need internet connection to get those data!', $this->id); ?>
  </td>
</tr>

<tr valign="top">
  <th scope="row"><?php _e('Inject analytics code?', $this->id); ?></th>
  <td colspan="3">  <input name="googleanalyticscounter[code]" type="radio" class="code" value="1"<?php echo intval($this->options['code']) == 1 ? ' checked="checked"' : ''; ?> /> ja 
  <input name="googleanalyticscounter[code]" type="radio" class="code" value="0"<?php echo intval($this->options['code']) == 0 ? ' checked="checked"' : ''; ?> /> nein<br /><?php _e('For that function it\'s required that your template calls <em>wp_footer();</em> or <em>wp_head();</em>', $this->id); ?></td>
</tr>

<tr valign="top">
  <th scope="row"><?php _e('Title', $this->id); ?></th>
  <td colspan="3"><input name="googleanalyticscounter[title]" type="text" id="" class="code" value="<?=$this->options['title']?>" /> <?php _e('Title is shown above the Widget. If left empty can break your layout in widget mode!', $this->id); ?></td>
</tr>

<tr valign="top">
  <th scope="row"><?php _e('Layout', $this->id); ?></th>
  <td colspan="3">
  <input name="googleanalyticscounter[layout]" type="radio" class="code" value="0"<?php echo intval($this->options['layout']) == 0 ? ' checked="checked"' : ''; ?> />
  <img src="<?=$this->url?>/img/layout0.gif" style="vertical-align:middle;" /><br /><br />
  <input name="googleanalyticscounter[layout]" type="radio" class="code" value="1"<?php echo intval($this->options['layout']) == 1 ? ' checked="checked"' : ''; ?> />
  <img src="<?=$this->url?>/img/layout1.gif" style="vertical-align:middle;" /><br /><br />
  <input name="googleanalyticscounter[layout]" type="radio" class="code" value="2"<?php echo intval($this->options['layout']) == 2 ? ' checked="checked"' : ''; ?> />
  <img src="<?=$this->url?>/img/layout2.gif" style="vertical-align:middle;" /><br /><br />
  <input name="googleanalyticscounter[layout]" type="radio" class="code" value="3"<?php echo intval($this->options['layout']) == 3 ? ' checked="checked"' : ''; ?> />
  <img src="<?=$this->url?>/img/layout3.gif" style="vertical-align:middle;" />
  </td>
</tr>

</table>

<p class="submit">
<input type="submit" name="Submit" value="<?php _e('save', $this->id); ?>" class="button" />
</p>
</form>

</div>
<?php
  }

  function updateOptions($options) {

    foreach($this->options as $k => $v) {
      if(array_key_exists( $k, $options)) {
        $this->options[ $k ] = trim($options[ $k ]);
      }
    }
        
		update_option($this->id, $this->options);
	}
  
  function loadOptions() {
    # delete_option($this->id);
    $this->options = get_option($this->id);

    if( !$this->options ) {
      $this->options = array(
        'installed' => time(),
        'username' => '',
        'password' => '',
        'account' => '',
        'layout' => 0,
        'code' => 0,
#        'last_check' => 0,
#        'visits' => 0,
        'username' => '',
        'password' => '',
        'title' => 'Visits'
			);

      add_option($this->id, $this->options, $this->name, 'yes');
    }
    
    // update to v0.4
    if(!array_key_exists('code', $this->options)) {
      $this->options['code'] = 0;
      $this->updateOptions($this->options);
    }
  }
  
  function addAdminFooter() {
  }
  
  function rgbColor(&$img, $rgb) {
    if($rgb[0] == '#') {
      $rgb = substr($rgb, 1);
    }
    
    $a = substr($rgb, 0, 2);
    $b = substr($rgb, 2, 2);
    $c = substr($rgb, 4, 2);

    return imagecolorallocate($img, hexdec($a), hexdec($b), hexdec($c));
  }
  
  function getCount() {
    include_once($this->path . '/lib/googleanalyticsapi.class.php');

    $api = new GoogleAnalyticsApi($this->options['username'], $this->options['password']);
    list($account_id, ) = explode('|', $this->options['account']);
    $api->account_id = $account_id;
	  
		$from = date('Y-m-d', strtotime('-1 day'));
    $to   = date('Y-m-d', strtotime('-1 day'));

    return $api->getData('ga:visitors', $from, $to);
  }

  function render() {
    clearstatcache();
    
    $create = false;
    
    if(!file_exists($this->cache_file)) {
      $create = true;
    }
    elseif(time() - filemtime($this->cache_file) > (3600 * 3)) {
      $create = true;
    }
    
    if($create) {
    
      $img = imagecreatefromgif($this->path. '/img/layout'. $this->options['layout']. '.gif');
#      $tmp = $this->rgbColor($img, 'ffffff');
      
      $layout = $this->layouts[$this->options['layout']];
      
      $font_color = $this->rgbColor($img, $layout['color']);

      $count = $this->getCount();

      if($count === false) {
        $count = 'Error!';
      }

      imagestring($img, $layout['font'], $layout['x'], $layout['y'], $count, $font_color);

      if(is_writeable($this->path. '/cache')) {
        imagegif($img, $this->cache_file);
      }
    }
    else {
      $img = imagecreatefromgif($this->cache_file);
    }

    header('Content-Type: image/gif');
    imagegif($img);
    exit;
  }

  function initWidget() {
    if(function_exists('register_sidebar_widget')) {
      register_sidebar_widget($this->title . ' Widget', array($this, 'showWidget'), null, 'widget_googleanalyticscounter');
    }
  }

  function showWidget( $args ) {
    extract($args);
    printf('%s%s%s%s%s%s', $before_widget, $before_title, $this->options['title'], $after_title, $this->getCode(), $after_widget);
  }

  function blogHeader() {
    printf('<meta name="%s" content="%s/%s" />' . "\n", $this->id, $this->id, $this->version);
    printf('<link rel="stylesheet" href="%s/styles/%s.css" type="text/css" media="screen" />'. "\n", $this->url, $this->id);
    
    if(intval($this->options['code']) == 1 && !$this->injected) {
      $this->inject();
    }
  }
  
  function inject() {
    $this->injected = true;
?>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try { var pageTracker = _gat._getTracker("<?php list(,$account_id) = explode('|', $this->options['account']); echo $account_id; ?>"); } catch(err) {}
</script>
<?php
  }
  
  function blogFooter() {
    if(intval($this->options['code']) == 1) {
      $this->inject();
    }
  }

  function getCode() {
      return sprintf('<div id="%s"><a href="http://www.yellingnews.com/wordpress-plugins#googleanalyticscounter" title="Google Analytics Counter" target="_blank" class="snap_noshots"><img src="%s/%s.php?img=1" /><div></a><small><a href="http://www.yellingnews.com/wordpress-plugins" target="_blank" class="snap_noshots">Plugin</a> by <a href="http://www.yellingnews.com" class="snap_noshots" target="_blank">Yellingnews</a></small></div></div>', $this->id, $this->url, $this->id);
  }
}

function googleanalyticscounter_display() {

  global $GoogleAnalyticsCounter;

  if(!isset($GoogleAnalyticsCounter)) {
    echo $GoogleAnalyticsCounter->getcode();
  }
}
endif;

if(@isset($_GET['img'])) {
  include_once(dirname(__FILE__). '/../../../wp-config.php');

  if(!isset($GoogleAnalyticsCounter)) {
    $GoogleAnalyticsCounter = new GoogleAnalyticsCounter();
  }

  $GoogleAnalyticsCounter->render();
}
else {
  add_action('plugins_loaded', create_function('$GoogleAnalyticsCounter_53kpl', 'global $GoogleAnalyticsCounter; $GoogleAnalyticsCounter = new GoogleAnalyticsCounter();'));
}

?>